var data = {count : 0},
	LENGTH = 2;

exports.index = function(req, res) {

	var query = getQueryString(req);

	if(!query.langType) data.type = 'zh-CN';
		else data.type = query.langType;

	if(query.dir) data.curDir = query.dir;
	else data.curDir = '';

	if(query.action){
		switch(query.action){
			case 'save':
			saveFile(req.body);
			res.json({"name":"hejun"});
			break;
			case 'import':
			copyFile(req, res);
			break;
			case 'translate':
			translate(req, res);
			break;
		}
	}else{
		data.count = 0;
		readDir(req,res);
		getConfig(req,res);
	}
  	
};

function translate(req, ress) {
	var query = require('querystring').stringify(req.body);
	http = require("http").get("http://fanyi.baidu.com/v2transapi?" + query, function(res){
		var html;
		res.on("data",function(data){
        	html+=data;
	    })
	    res.on("end",function(){
	    	ress.json(JSON.parse(html.slice(9)));	
	    })
	}).on('error', function(e){ 
		console.log("Got error: " + e.message); 
	});
}

function copyFile(req, res){
	var dir = getRootDir() + '/pubLic/lang/' + data.curDir,	fs = require('fs');
	fs.readFile(dir + '/' + 'zh-CN.lang', function(err, file){
		data.CurLangFile = JSON.parse(file.toString());
		fs.writeFile(dir + '/' + data.type + '.lang', file, function(err){
		    if(err) console.log('写文件操作失败');
		    else    console.log('写文件操作成功');
		    data.count = 0;
		    readDir(req,res);
			getConfig(req,res);
		});
		
	});
}

function saveFile(datas){
	var file = [getRootDir(),'/pubLic/lang/',data.curDir,'/',data.type,'.lang'].join('');
	require("fs").writeFile(file, datas.data, function(err){
	    if(err) console.log('写文件操作失败');
	    else 	console.log('写文件操作成功');
	});
}

function getQueryString(req){
	return require("querystring").parse(require("url").parse(req.url).query);
}

function getCurrentLangFile(req, res){
	var dir = getRootDir() + '/pubLic/lang/' + data.curDir;
	require('fs').readFile(dir + '/' + data.type + '.lang', function(err, file){
		if(err) console.log(err);
		data.CurLangFile = JSON.parse(file.toString());
		data.count++;
		if(data.count === LENGTH) response(req, res);
	});
}

function response(req,res){
	if(data.count === LENGTH) res.render("langServer", data);
}

function readDir(req,res){
 	require('fs').readdir(getRootDir() + '/public/lang', function(err, files){
 		if(err) console.log(err);	
	    data.dir = files;
	    if(!data.curDir) data.curDir = files[0];
	    getCurrentLangFile(req, res);
	});  
}

function getConfig(req,res){
	require('fs').readFile(getRootDir() + '/config.json',function(err, file){
		if(err) console.log(err);
		data.langType = JSON.parse(file.toString()).lang;
		data.count++;
		if(data.count === LENGTH) response(req, res);
	})
}

function getRootDir(){
	return __dirname.slice(0, __dirname.indexOf("HNA-logistics-cus-ui") + "HNA-logistics-cus-ui".length);
}